'use client';

import { useEffect, useState } from 'react';
import { useRouter, usePathname } from 'next/navigation';

export default function AuthGuard({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const pathname = usePathname();
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const checkAuth = () => {
      // 检查localStorage中的token
      const localToken = localStorage.getItem('admin-token');
      
      // 检查cookie中的token
      const cookieValue = document.cookie
        .split('; ')
        .find(row => row.startsWith('admin-token='))
        ?.split('=')[1];

      const authenticated = localToken === 'authenticated' || cookieValue === 'authenticated';
      
      console.log('客户端认证检查', { 
        pathname, 
        localToken, 
        cookieValue, 
        authenticated 
      });

      if (pathname === '/admin/login') {
        // 如果已认证且在登录页，重定向到管理后台
        if (authenticated) {
          router.replace('/admin');
        } else {
          setIsLoading(false);
        }
      } else if (pathname.startsWith('/admin')) {
        // 如果未认证且在管理页面，重定向到登录页
        if (!authenticated) {
          router.replace('/admin/login');
        } else {
          setIsAuthenticated(true);
          setIsLoading(false);
        }
      } else {
        setIsLoading(false);
      }
    };

    checkAuth();
  }, [pathname, router]);

  // 登录页面或非管理页面不需要loading
  if (pathname === '/admin/login' || !pathname.startsWith('/admin')) {
    return <>{children}</>;
  }

  // 管理页面需要认证检查
  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-2 text-gray-600">正在验证身份...</p>
        </div>
      </div>
    );
  }

  if (!isAuthenticated) {
    return null; // 重定向中
  }

  return <>{children}</>;
}